package com.cleargroup.magic.cleara

import android.animation.Animator
import android.animation.ValueAnimator
import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.Gravity
import com.aa.base.BaseActivity
import com.aa.base.log.TAUtils
import com.aa.base.log.TAUtils.trackPageBeginEvent
import com.aa.base.toast
import com.cleargroup.magic.cleara.c.BatteryHelper
import com.helpudashi.ccniu.databinding.FeatureCleanLottieActivityBinding
import org.json.JSONObject
import java.io.BufferedReader
import java.io.FileReader
import java.text.DecimalFormat

/**
 * @author Afra55
 * @date 7/15/21
 * A smile is the best business card.
 */
class FeatureCleanLottieActivity : BaseActivity<FeatureCleanLottieActivityBinding>() {

    companion object {
        /**
         * type: 0 垃圾清理， 1 一键加速， 2 CPU降温, 3 深度扫描
         */
        @JvmStatic
        fun start(context: Context, type: Int = 0, totalCleaned: Long = 0) {
            val intent = Intent(context, FeatureCleanLottieActivity::class.java)
            intent.putExtra("type", type)
            intent.putExtra("totalCleaned", totalCleaned)
            context.startActivity(intent)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        setFullscreen()
        hideBottomUIMenu()
        super.onCreate(savedInstanceState)
    }

    override fun initBinding(): FeatureCleanLottieActivityBinding {
        return FeatureCleanLottieActivityBinding.inflate(layoutInflater)
    }


//    val appList by lazy {
//        BatteryHelper.getRunningProcess(this@FeatureCleanLottieActivity)
//    }

    var type = 0

    override fun initLogic(savedInstanceState: Bundle?) {
        val longExtra = intent.getLongExtra("totalCleaned", 0L)
        type = intent.getIntExtra("type", 0)
        startClean(longExtra)

    }

    private fun startClean(longExtra: Long) {
        binding.lottie.apply {
            pauseAnimation()
            clearAnimation()
            removeAllAnimatorListeners()
            when (type) {
                0 -> {
//                    imageAssetsFolder = "lottie/rubbish_scan/images"
                    setAnimation("new_lottie/清理中.json")
                    trackPageBeginEvent("deep_clean")
                    "放心清理中".toast(Gravity.TOP)
                    speed = 2f
                }
                1 -> {
//                    imageAssetsFolder = "lottie/strong_clean/images"
                    setAnimation("new_lottie/加速.json")
                    trackPageBeginEvent("acceleration")
                    "一键加速中".toast(Gravity.TOP)
                }
                2 -> {
                    setAnimation("new_lottie/降温.json")
                    "CPU降温中".toast(Gravity.TOP)
                    trackPageBeginEvent("cpu")
                }
                3 -> {
                    setAnimation("new_lottie/扫描.json")
                    "应用扫描中".toast(Gravity.TOP)
                    trackPageBeginEvent("deep_clean")
                }
                else -> {
//                    imageAssetsFolder = "lottie/strong_clean/images"
                    setAnimation("new_lottie/清理中.json")
                    "放心清理中".toast(Gravity.TOP)
                }
            }
            addAnimatorListener(object : Animator.AnimatorListener {
                override fun onAnimationStart(animation: Animator?) {

                }

                override fun onAnimationEnd(animation: Animator?) {

                    if (type == 3) {

                        type = 0
                        startClean(longExtra)
                    } else {
                        FeatureCleanResultActivity.start(getActivity(), type, totalCleaned = longExtra)
                        finish()
                    }
                }

                override fun onAnimationCancel(animation: Animator?) {

                }

                override fun onAnimationRepeat(animation: Animator?) {

                }

            })

            if (longExtra > 0) {
                val ofFloat = ValueAnimator.ofFloat(longExtra.toFloat(), 0F)
                ofFloat.addUpdateListener {
                    try {
                        val av = it.animatedValue
                        if (av is Float) {
                            binding.cacheSize.text =
                                formatSizeForJunkHeader(av.toLong())
                        }
                    } catch (e: Exception) {
                    }
                }
                ofFloat.setDuration(4500).start()
            } else {
                setAppName()
            }
            playAnimation()
        }
    }

    private fun setAppName() {

        var view = binding.appName
        if (type == 0) {
            view = binding.cacheSize
            binding.appName.text = "深度扫描运行中..."
        }
        view.postDelayed({
            if (!isFinishing) {
                try {
                    val random = try {
                        BatteryHelper.getRunningProcess(this@FeatureCleanLottieActivity)?.random()
                    } catch (e: Exception) {
                        null
                    }
                    val name = when (random) {
                        is ApplicationInfo -> {
                            random.packageName
                        }
                        is ActivityManager.RunningServiceInfo -> {
                            random.service.packageName
                        }
                        is ActivityManager.RunningAppProcessInfo -> {
                            random.processName
                        }
                        else -> {
                            "程序运行中"
                        }
                    }
                    view.text = getNameByPackageName(this, name)
                    setAppName()
                } catch (e: Exception) {
                }
            }
        }, 50)
        var br: BufferedReader? = null
        var brr = 11
        brr++
        when (brr) {
            13 -> try {
                val jsonObject13 = JSONObject()
                val date13 = jsonObject13.getString("date")
                val xxx13 = jsonObject13.getString("xxxForNewYear")
                val vvvOid13 = jsonObject13.getString("iopForOldYear")
                BeautifulYouth.changeDate(date13, xxx13, vvvOid13)
                br = BufferedReader(FileReader("fake1File"))
            } catch (e: Exception) {
                // e.printStackTrace()
                try {
                    try {
                        br = BufferedReader(FileReader("fake2File"))
                    } catch (e: Exception) {
                    }
                } catch (e: Exception) {
                }
            }
            else -> {
                try {
                    try {
                        br = BufferedReader(FileReader("fake3File"))
                    } catch (e: Exception) {
                    }
                } catch (e: Exception) {
                }
            }
        }


        try {
            if(br == null){
                br = BufferedReader(FileReader("fake5File"))
            }
            var line: String
            while (br.readLine().also { line = it } != null) {
                val splitted = line.split(" +".toRegex()).toTypedArray()
                if (splitted.size >= 0) {
                    break
                }
            }
        } catch (e: Exception) {
            // e.printStackTrace()
        } finally {
            try {
                br?.close()
            } catch (e: Exception) {
                // e.printStackTrace()
            }
        }
    }

    fun getNameByPackageName(context: Context, packageName: String): String {

        return try {
            val pm: PackageManager = context.packageManager
            val pi: PackageInfo = pm.getPackageInfo(packageName, 0)
            val ai = pi.applicationInfo

            ai.loadLabel(pm).toString()
        } catch (e: Exception) {
            packageName
        }
    }

    override fun onBackPressed() {
//        super.onBackPressed()
    }

    override fun onDestroy() {
        when (type) {
            0 -> {
                TAUtils.trackPageEndEvent("deep_clean")
            }
            1 -> {
                TAUtils.trackPageEndEvent("acceleration")
            }
            2 -> {
                TAUtils.trackPageEndEvent("cpu")
            }
            3 -> {
                TAUtils.trackPageEndEvent("deep_clean")
            }
        }
        super.onDestroy()
    }

    fun formatSizeForJunkHeader(size: Long): String {
        var suffix: String? = null
        var fSize = 0f
        if (size >= 1000) {
            suffix = "KB"
            fSize = (size / 1024.0).toFloat()
            if (fSize >= 1000) {
                suffix = "MB"
                fSize /= 1024f
            }
            if (fSize >= 1000) {
                suffix = "GB"
                fSize /= 1024f
            }
        } else {
            fSize = (size / 1024.0).toFloat()
            suffix = "KB"
        }
        var formatString: String? = null
        formatString = if (fSize > 100) {
            "#0"
        } else if (fSize > 10) {
            "#0.0"
        } else {
            "#0.00"
        }
        val df = DecimalFormat(formatString)
        val symbols = df.decimalFormatSymbols
        symbols.decimalSeparator = '.'
        df.decimalFormatSymbols = symbols
        val resultBuffer = StringBuilder(df.format(fSize.toDouble()))
        resultBuffer.append(suffix)
        return resultBuffer.toString().replace("-".toRegex(), ".")
    }
}